package com.yiwei.zhh.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.TextSwitcher;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class NoticeView extends TextSwitcher {

    private List mList = new ArrayList<>();
    private int mIndex = 0;
    private int mTicks = 5;

    private Animation mInUp = anim(1.5f, 0);
    private Animation mOutUp = anim(0, -1.5f);

    private Animation mInDown = anim(-1.5f, 0);
    private Animation mOutDown = anim(0, 1.5f);

    public NoticeView(Context context) {
        this(context, null);
    }

    public NoticeView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setInAnimation(mInUp);
        setOutAnimation(mOutUp);

        setFactory(new ViewFactory() {
            @Override
            public View makeView() {
                TextView tv = new TextView(getContext());
                tv.setTextColor(0xFFffffff);
                tv.setSingleLine(true);
                return tv;
            }
        });
        postDelayed(new Runnable() {
            @Override
            public void run() {
                tick();
                postDelayed(this, 1000);
            }
        }, 1000);
    }


    private void resetTick() {
        mTicks = 5;
    }
    private void tick() {
        if (mTicks > 0) {
            mTicks--;
            return;
        }
        resetTick();
        if (mList == null || mList.size() < 1) {
            return;
        }
        mIndex = (mIndex+1) % mList.size();
        setText(mList.get(mIndex).toString());
    }

    private Animation anim(float from, float to){
        final TranslateAnimation translate = new TranslateAnimation(0, 0f, 0, 0f, Animation.RELATIVE_TO_PARENT, from, Animation.RELATIVE_TO_PARENT, to);
        translate.setDuration(800);
        translate.setFillAfter(false);
        translate.setInterpolator(new LinearInterpolator());
        return translate;
    }

    public <T extends Object> T getCurrent() {
        return (T) mList.get(mIndex);
    }

    public List getList() {
        return mList;
    }

    public void setList(List list) {
        mList = list;
        mIndex = 0;
        resetTick();
        if (mList == null || mList.size() < 1) {
            return;
        }
        setText(mList.get(mIndex).toString());
    }

    public int getIndex() {
        return mIndex;
    }

    public void previous() {
        setInAnimation(mInDown);
        setOutAnimation(mOutDown);
    }

    public void next() {
        setInAnimation(mInUp);
        setOutAnimation(mOutUp);
    }


}